package P3;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;


/**
 * 基于线程的Echo客户端/服务器程序设计
 * 3.1基于线程的Echo客户端/服务器程序设计
 * 3.1.1服务端程序（同步）:
 */
public class EchoServer {
    public static void main(String[] args) {
        try {
            // 创建 ServerSocket 实例并绑定到指定端口
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("Echo 服务器已启动,正在监听 8888 端口...");

            while (true) {
                // 等待客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("已接受来自客户端的连接: " + clientSocket.getInetAddress().getHostAddress());

                // 创建新线程处理客户端请求
                new Thread(() -> {
                    try {
                        // 获取输入/输出流
                        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

                        String message;
                        while ((message = in.readLine()) != null) {
                            // 同步方法:发送数据到客户端
                            sendMessage(out, message);
                            System.out.println("已回显数据到客户端: " + message);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            // 关闭客户端连接
                            clientSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static synchronized void sendMessage(BufferedWriter out, String message) throws IOException {
        // 同步方法:将接收到的数据回显给客户端
        out.write(message + "\n");
        out.flush();
    }
}